<template>
  <div ref="chart" style="width: 100%; height: 100%"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'ProfitChart',
  // 通过 props 接收父组件传递的数据：
  props: {
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    };
  },
  // 当父组件的 chartData 变化时（通过 watch 监听），子组件会重新渲染图表：
  watch: {
    chartData: {
      deep: true,
      handler() {
        this.initChart();
      }
    }
  },
  // 子组件在 mounted 生命周期钩子中调用 initChart() 方法，使用 ECharts 渲染图表：
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    initChart() {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart);
      }

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartData.dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          name: '利润(元)'
        },
        series: [
          {
            name: '利润',
            type: 'bar',
            data: this.chartData.profits,
            itemStyle: {
              color: params => {
                return params.value >= 0 ? '#67C23A' : '#F56C6C';
              }
            },
            label: {
              show: true,
              position: 'top',
              formatter: params => {
                return params.value >= 0 ? `+${params.value}` : params.value;
              }
            }
          }
        ]
      };

      this.chart.setOption(option);
      window.addEventListener('resize', this.resizeChart);
    },
    resizeChart() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  }
};
</script>